export enum MsgType {
    SUCCESS = "success",
    ERROR = "error",
    INFO = "info",
    WARNING = "warning"
}

export interface Option {
    message: string;
    time?: number; // 默认 3s
    type?: MsgType;
}

let container: HTMLElement | null = null

function createContainer() {
    container = document.createElement("div")
    container.className = "message-container"
    document.body.appendChild(container)
}

function showMessage(option: Option) {
    if (!container) createContainer()

    const { message: msg, time = 3, type = MsgType.INFO } = option
    const div = document.createElement("div")
    div.className = `message-item ${type}`
    div.innerHTML = `
    <span class="icon">${getIcon(type)}</span>
    <span class="text">${msg}</span>
  `

    container!.appendChild(div)

    // 动画：强制触发 reflow
    requestAnimationFrame(() => {
        div.classList.add("show");
    })

    setTimeout(() => {
        div.classList.remove("show");
        div.classList.add("hide");
        div.addEventListener("transitionend", () => {
            if (div.parentNode) {
                container!.removeChild(div)
            }
        })
    }, time * 1000)
}

// 主函数
export const message = (option: Option) => {
    showMessage(option)
}

// 挂载几个静态方法
message.success = (msg: string, time = 3) => {
    showMessage({ message: msg, type: MsgType.SUCCESS, time })
}

message.error = (msg: string, time = 3) => {
    showMessage({ message: msg, type: MsgType.ERROR, time })
}

message.info = (msg: string, time = 3) => {
    showMessage({ message: msg, type: MsgType.INFO, time })
}

message.warning = (msg: string, time = 3) => {
    showMessage({ message: msg, type: MsgType.WARNING, time })
}

function getIcon(type: MsgType) {
    switch (type) {
        case MsgType.SUCCESS:
            return "✔️"
        case MsgType.ERROR:
            return "❌"
        case MsgType.WARNING:
            return "⚠️"
        default:
            return "ℹ️"
    }
}
